<?php

class LoginController extends Zend_Controller_Action
{
 	protected $_users;

    public function init()
    {
        $this->_users = new Application_Model_Users();
    }

	public function  getFormLogin()
    {
        return new Application_Form_Login(array(
            'action' => $this->_helper->url('process', 'login'),
            'method' => 'post',
        ));
    }

    public function getAuthAdapter(array $params)
    {
		$dbAdapter = new Zend_Db_Adapter_Pdo_Sqlite(array('dbname' =>'webdb'));

		$authAdapter = new Zend_Auth_Adapter_DbTable(Zend_Db_Table_Abstract::getDefaultAdapter(),
	    					'users',
	  						  'username',
	   							 'password');
		$authAdapter->setIdentity($params["username"])->setCredential(md5($params["password"]));
		return $authAdapter;
    }

	public function  preDispatch()
    {
        if (Zend_Auth::getInstance()->hasIdentity()) {
            // If the user is logged in, we don't want to show the login form;
            // however, the logout action should still be available
            if ('logout' != $this->getRequest()->getActionName()) {
                $this->_helper->redirector('index', 'index');
            }
        } else {
            // If they aren't, they can't logout, so that action should
            // redirect to the login form
            if ('logout' == $this->getRequest()->getActionName()) {
                $this->_helper->redirector('index');
            }
        }
    }

  	public function  indexAction()
    {
        $this->view->title = 'Вход в системата';
        $this->view->headTitle($this->view->title);

        $this->view->form = $this->getFormLogin();
    }


 	public function  processAction()
    {
        $request = $this->getRequest();
        
        if (!$request->isPost()) {
            return $this->_helper->redirector('index');
        }

        $form = $this->getFormLogin();
        if (!$form->isValid($request->getPost())) {
            $this->view->form = $form;
            return $this->render('index');
        }

        $adapter = $this->getAuthAdapter($form->getValues());
        $auth    = Zend_Auth::getInstance();
        $result  = $auth->authenticate($adapter);
        if (!$result->isValid()) {
            // Invalid credentials
            $form->setDescription('Invalid credentials provided');
            $this->view->form = $form;
            return $this->render('index');
        }

		$storage = $auth->getStorage();
		$storage->write($adapter->getResultRowObject(array('id', 'username')));

        $this->_helper->redirector('index', 'index');
    }

  	public function  logoutAction()
    {
        Zend_Auth::getInstance()->clearIdentity();
        $this->_helper->redirector('index'); // back to login page
    }

	public function  registerAction()
    {
        $this->view->title = 'Потребителска регистрация';
        $this->view->headTitle($this->view->title);

        $form = new Application_Form_User();
        $form->removeElement('id');

     	if ($this->getRequest()->isPost()) {
            $formData = $this->getRequest()->getPost();

            if ($form->isValid($formData)) {
                $this->_users->createUser($form->getValues());

                $this->view->registered = 1;
            } else {
                $form->populate($formData);
            }
        }
        $this->view->form = $form;
    }

}

